RedisConfig = require('../config').redis
Redis = require 'redis'
Client = Redis.createClient RedisConfig.port
Logger = require('log4js').getLogger()
_ = require 'underscore'


###*
 * [initRedisClient 初始化redis client，将原来client的函数添加到redisClient中，增加对client的调用会先判断是否已连接]
 * @param  {[type]} redisClient [新的redis client]
 * @param  {[type]} client      [原有的redis client]
###
initRedisClient = (redisClient, client) ->
  functions = _.functions client
  _.each functions, (func, i) ->
    redisClient[func] = () ->
      args = Array.prototype.slice.call arguments
      if client.connected
        client[func].apply client, args
      else
        cbf = args.pop()
        if _.isFunction cbf
          cbf
            code : -1
            msg : 'redis is not connected'

#redis client event#
Client.on 'ready', (err) ->
  if err
    Logger.error "redis.js redis ready event: #{JSON.stringify(err)}"
  Logger.info 'redis ready'
Client.on 'error', (err) ->
  if err
    Logger.error "redis.js redis error event: #{JSON.stringify(err)}"

redisClient = {}
initRedisClient redisClient, Client
 
module.exports = redisClient 
